import {getCoupon, postCoupon, putCoupon, getProducts, postCouponV2, putCouponV2} from '@/base/api/CouponsApi';
import {Agent} from '@/base/model/Agent';
import {deepAssign} from '@/base/util/Objects';
import {Company} from '@/base/model/Company';
import {getAgentList} from '@/base/api/AgentApi';
import {getCompanyList} from '@/base/api/CompanyApi';
import {Page} from '@/base/Page';
import {getMemberList, selectMemberByAgentId} from '@/base/api/MemberApi';

export class FormBloc {
  model: any = {
    companyId: 0,
    agentId: 1,
    CouponName: '',
    Condition: 0,
    Reduce: 0,
    TimeRadio: 0,
    DayNum: 0,
    startTime: '',
    endTime: '',
    MemberRadio: 1,
    targetAccounts: [],
    targetAccountsIn: [],
    targetAccountsOut: [],
    ProductRadio: 1,
    targetProducts: []
  };
  modelEdit: any = {
    couponId: 0,
    companyId: 0,
    agentId: 0,
    couponName: '',
    condition: 0,
    reduce: 0,
    TimeRadio: 0,
    DayNum: 0,
    startTime: '',
    endTime: '',
    MemberRadio: 1,
    targetAccounts: [],
    targetAccountsIn: [],
    targetAccountsOut: [],
    ProductRadio: 1,
    targetProducts: []
  };

  loading = false;
  num: number = 0;
  memberList: any=[];
  memberSet=new Set();
  sortList: any = [];
  companyList: any = [];
  CurrentMemberRadio = 0;
  CurrentMemberGroup = [];
  MemberString = '';
  // sortId: number = 0;
  // modelId: number = 0;
  isDetail = false;
  isinfo = false;
  type: string | undefined;
  company: Page<Company> = new Page<Company>([], 0, 1, 10, 0, []);
  angent: Page<Agent> = new Page<Agent>([], 0, 1, 15, 0, []);

  load(couponId: number) {
    return getCoupon({couponId})
      .then((res) => {
        this.modelEdit.couponId = couponId;
        this.modelEdit.companyId = res.data.companyId;
        this.modelEdit.agentId = res.data.agentId;
        this.modelEdit.condition = res.data.condition;
        this.modelEdit.reduce = res.data.reduce;
        this.modelEdit.couponName = res.data.couponName;
        this.modelEdit.TimeRadio = res.data.TimeRadio;
        this.modelEdit.DayNum = res.data.daynum;
        this.modelEdit.startTime = res.data.startTime;
        this.modelEdit.endTime = res.data.EndTime;
        this.modelEdit.MemberRadio = res.data.memberRadio;
        this.CurrentMemberRadio = res.data.memberRadio;
        if (res.data.CouponMember) {
          res.data.CouponMember.forEach(x => {
            this.modelEdit.targetAccounts.push(parseInt(x).toString());
            this.modelEdit.targetAccountsIn.push(parseInt(x).toString());
            // @ts-ignore
            this.CurrentMemberGroup.push(parseInt(x).toString());
          })
        } else if (res.data.memberGroup) {
          res.data.memberGroup.forEach(x => {
            this.modelEdit.targetAccounts.push(parseInt(x).toString());
            this.modelEdit.targetAccountsIn.push(parseInt(x).toString());
            // @ts-ignore
            this.CurrentMemberGroup.push(parseInt(x).toString());
          })
        }
        if (this.modelEdit.targetAccountsIn) {
          this.MemberString = this.modelEdit.targetAccountsIn.join(',');
        }
        return res;
      }).finally(() => {
        this.loading = false
      })
  }
  getProducts(couponId: number) {
    return getProducts({couponId})
      .then((res) => {
        // @ts-ignore
        let json = JSON.parse(res.data);console.log(json);
        this.modelEdit.ProductRadio = json.errMsg.ProductRadio;
        if (json.errMsg.targetProduct) {
          this.modelEdit.targetProducts = JSON.parse(json.errMsg.targetProduct);
        }
        console.log(this.modelEdit.targetProducts)
        return res;
      }).finally(() => {
        this.loading = false
      })
  }
  getAllSort(pageIndex: number, pageSize: number, sortDirection: string, companyId) {
    this.loading = true;
    let that = this;
    return getAgentList({
      pageIndex,
      pageSize,
      companyId: companyId
    }).then((res) => {
      this.sortList = res.data.items.map(function (item) {
        const obj = {id: 0, agentName: ''};
        // @ts-ignore
        obj.id = item.id;
        obj.agentName = item.agentName;
        return obj;
      });
      return this.sortList;
    }).finally(() => {
      this.loading = false;
    });
  }

  getCompanyList(pageIndex: number,
                 pageSize: number,
                 sortDirection: string) {
    return getCompanyList({pageIndex, pageSize, sortDirection, name: '', createBegin: ''})
      .then((res) => {
        deepAssign(this.company, res.data);
        this.companyList = res.data.items.map(item => {
          let obj = {companyId: 0, companyName: ''};
          obj.companyId = item.id;
          obj.companyName = item.name;
          return obj
        });
        return res;
      }).finally(() => {
        this.loading = false;
      });
  }
  getDaynum(stStr, etStr) {
    let st = new Date(stStr);
    let et = new Date(etStr);
    let timeDifference = et.getTime() - st.getTime();
    this.model.DayNum = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  }
  getDaynum2(stStr, etStr) {
    let st = new Date(stStr);
    let et = new Date(etStr);
    let timeDifference = et.getTime() - st.getTime();
    this.modelEdit.DayNum = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  }
  formatDate(date) {
    if (date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    } else {
      return ``;
    }
  }
  addModel(model) {
    this.loading = true;
    return postCouponV2({
      companyId: model.companyId,
      agentId: model.agentId,
      couponName: model.CouponName,
      condition: parseInt(model.Condition),
      reduce: parseInt(model.Reduce),
      daynum: parseInt(model.DayNum),
      startTime: this.formatDate(model.startTime),
      memberRadio: model.MemberRadio,
      targetAccounts: model.targetAccounts,
      targetAccountsIn: model.targetAccountsIn,
      targetAccountsOut: model.targetAccountsOut,
      productRadio: model.ProductRadio,
      targetProducts: model.targetProducts
    }).then((res) => {
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }
  editModel(model) {
    this.loading = true;
    return putCouponV2({
      couponId: model.couponId,
      companyId: model.companyId,
      agentId: model.agentId,
      couponName: model.couponName,
      condition: parseInt(model.condition),
      reduce: parseInt(model.reduce),
      daynum: parseInt(model.DayNum),
      startTime: this.formatDate(model.startTime),
      memberRadio: model.MemberRadio,
      targetAccounts: model.targetAccounts,
      targetAccountsIn: model.targetAccountsIn,
      targetAccountsOut: model.targetAccountsOut,
      productRadio: model.ProductRadio,
      targetProducts: model.targetProducts
    }).then((res) => {
      return res;
    }).finally(() => {
      this.loading = false;
    });
  }

  reset() {
    location.reload();
  }
  // getMemberData(companyId?:number[]) {
  //   getMemberList({
  //     companyId,
  //     pageIndex: 1,
  //     pageSize: 40000
  //   }).then((res) => {
  //     this.memberList = [];
  //     res.data.forEach((item) => {
  //       this.memberList.push({
  //         key: item.id.toString(),
  //         label: item.phone,
  //         description: 'The desc of content  ',
  //         disabled: false
  //       })
  //     })
  //   }).finally(() => {
  //     this.loading = false;
  //   });
  // }

  getMemberData(companyId?:number[]) {
    getMemberList({
      companyId,
      pageIndex: 1,
      pageSize: 40000
    }).then((res) => {
      this.memberList = [];
      this.memberSet = new Set();
      res.data.forEach((item) => {
        this.memberList.push(
          item.phone
        )
      })
      this.memberSet = new Set(this.memberList);
    }).finally(() => {
      this.loading = false;
    });
  }

  // getMemberByAgentId(agentId) {
  //   selectMemberByAgentId({
  //     agentId: agentId
  //   }).then((res) => {
  //     this.memberList = [];
  //     res.data.forEach((item) => {
  //       this.memberList.push({
  //         key: item.id.toString(),
  //         label: item.phone,
  //         description: 'The desc of content  ',
  //         disabled: false
  //       })
  //     })
  //   }).finally(() => {
  //     this.loading = false;
  //   });
  // }

}
